package cn.qayy.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.qayy.dao.PlanLogMapper;
import cn.qayy.dao.PlanMapper;
import cn.qayy.dto.PlanLogDTO;
import cn.qayy.po.Plan;
import cn.qayy.po.PlanLog;
import cn.qayy.po.User;
import cn.qayy.service.IPlanLogService;
import cn.qayy.utils.BeanToMapUtils;
import cn.qayy.utils.DownLoadUtil;

/***
 * @author wangyu
 *
 */
@Service("planLogServiceImpl")
public class PlanLogServiceImpl implements IPlanLogService {

	@Resource
	private PlanLogMapper planLogMapper;
	
	@Resource
	private PlanMapper planMapper;
	
	@Override
	public PageInfo<PlanLog> selectPlanLogBy(PlanLogDTO dto) throws Exception {
		if (dto != null) {
			DownLoadUtil.set("PlanLogDTO",dto);
			List<PlanLog> list = planLogMapper.selectPlanLogBy(dto);
			Integer planId = Integer.valueOf(dto.getId());
			Plan plan = planMapper.selectByPrimaryKey(planId);
			if(plan!=null) {
				PlanLog log = new PlanLog();
				log = log.setByPlan(plan);
				list.add(log);
			}
			PageHelper.startPage(dto.getPageNumber(), dto.getPageSize());
			PageInfo<PlanLog> pageInfo = new PageInfo<PlanLog>(list);
			return pageInfo;
		}
		return null;
	}

	@Override
	public int insertByList(List<Plan> list,HttpServletRequest request) throws Exception{
		String logAction  = (String)request.getAttribute("logAction");
		User user = (User)request.getSession().getAttribute("user");
		List<PlanLog> planlog = new ArrayList<PlanLog>();
		List<Plan> planlist = planMapper.selectBeforeByIds(list);
		for(Plan plan :planlist) {
			PlanLog log = new PlanLog();
			log = log.setByPlan(plan);
			log.setLogDataer(user.getUser_name());
			log.setLogTime(new Date().toString());
			log.setLogType(logAction);
			planlog.add(log);
		}
		return planLogMapper.insertByList(planlog);
	}
	
	public List<Map<String, Object>> selectListByDown(PlanLogDTO dto){
		List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
		try {
			List<PlanLog> list = planLogMapper.selectPlanLogBy(dto);
			
			Integer planId = Integer.valueOf(dto.getId());
			Plan plan = planMapper.selectByPrimaryKey(planId);
			if(plan!=null) {
				PlanLog log = new PlanLog();
				log = log.setByPlan(plan);
				list.add(log);
			}
			
			//把对象集合转为Map
			for(PlanLog log : list) {
				Map<String, Object> map;
				map = BeanToMapUtils.objectToMap(log);
				retList.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retList;
	}

}
